package java.util.concurrent;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 允许单个/多个线程等待 await(), 其他线程 countDown()
 * countDown() 次数达到构造方法参数值大小时 (内部是 countDown == 0), 所有等待的线程释放
 * 当 countDown == 0 后, 再次调用 await() 会立即返回, 不阻塞
 * 不可被重用 (即 countDown 值不能被重置)
 */
public class CountDownLatch {

    /**
     * AQS State
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        // state == 0 时, 释放
        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    private final Sync sync;

    /**
     * @param count 线程释放前, countDown() 被调用的次数
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    /**
     * 线程进入等待状态, 直到 count == 0
     * 如果调用前 count == 0, 那么 await 直接返回, 不阻塞
     */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * 与上面方法类似, 不过有最长等待时间的限制
     * 超过等待的最长时间, 会释放等待状态
     */
    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    /**
     * 让计数自减 1
     * 如果当前计数是 0, 那么什么也不做
     */
    public void countDown() {
        sync.releaseShared(1);
    }

    /**
     * 返回当前的计数
     */
    public long getCount() {
        return sync.getCount();
    }

    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}
